package com.apes.enquiry.supplier.baturu.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.enquiry.enquiry.model.Quote;
import com.apes.enquiry.enquiry.repository.QuoteRepository;
import com.apes.enquiry.supplier.baturu.BaturuApi;
import com.apes.enquiry.supplier.baturu.model.*;
import com.apes.enquiry.supplier.baturu.repository.BaturuInquireRepository;
import com.apes.enquiry.supplier.baturu.repository.BaturuPurshPriceLogRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.generator.service.SequenceService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.outbox.OutboxSubscriberService;
import com.apes.framework.util.DateUtil;
import com.apes.framework.util.MapUtil;
import com.apes.framework.util.Tools;
import com.apes.pi.service.PiManager;
import com.apes.scm.masterdata.enumeration.model.BusinessParam;
import com.apes.scm.masterdata.enumeration.repository.BusinessParamRepository;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

@Service("baturuInquireService")
public class BaturuInquireService extends DomainService {
    @Autowired
    private BaturuInquireRepository baturuInquireRepository;
    @Autowired
    private BaturuApi baturuApi;
    @Autowired
    private PiManager piManager;
    @Autowired
    private BaturuAccountInfoService baturuAccountInfoService;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private QuoteRepository quoteRepository;
    @Autowired
    private BusinessParamRepository businessParamRepository;

    public void save() {
        this.innerSave(null);
    }

    private BaturuInquire innerSave(BaturuInquire baturuInquire) {
        return baturuInquireRepository.saveAndFlush(baturuInquire);
    }

    // 服务方案转巴图鲁询价 - 保存数据到供应商平台
    public void servicePlanToInquire(SimpleRequest request) {
        Map baturuPriceData = request.getMap();
        if (StringUtils.isEmpty(baturuAccountInfoService.queryUserKey(baturuPriceData.get("store").toString())) || baturuPriceData.get("inquiryDetails") == null) return;

        // 重复配件不传送
        List distinctBaturuItems = this.distinctPartName(((List) baturuPriceData.get("inquiryDetails")));
        baturuPriceData.put("inquiryDetails", distinctBaturuItems);

        // 序列化对象
        BaturuInquire baturuInquire = Tools.map(baturuPriceData, BaturuInquire.class);
        SpringManager.getBean(MapUtil.class).refresh(baturuInquire);
        baturuInquire = this.innerSave(baturuInquire);

        String batuluInquireId = this.pushBaturuInquire(baturuPriceData);
        baturuInquire.setBaturuInquire(batuluInquireId);
        //保存巴图鲁返回的询价单号到报价结果
        saveQuote(baturuPriceData, batuluInquireId);
        this.innerSave(baturuInquire);
    }

    /**
     * 保存巴图鲁返回的询价单号到报价结果
     * @param baturuPriceData
     * @param batuluInquireId
     */
    private void saveQuote(Map baturuPriceData, String batuluInquireId){
        BusinessParam supplierNumber = businessParamRepository.findAllByQueryKey("baturuSupplierNumber").get(0);
        String[] split = supplierNumber.getValue().replace("[", "").replace("]", "").split(",");
        //根据供应商id和询价单号获取报价单
        Quote quote = quoteRepository.findOneByEnquiryAndSupplier(baturuPriceData.get("origin").toString(), split[0]);

        //Quote quote = new Quote();
        quote.setModelId(batuluInquireId);
        //quote.setEnquiryId(baturuPriceData.get("origin").toString());
        //quote.setState("ing");
//        if (!CollectionUtils.isEmpty(JSONArray.parseArray(baturuPriceData.get("inquiryDetails").toString()))){
//            String partyRoleId = JSONObject.parseObject(JSONArray.parseArray(baturuPriceData.get("inquiryDetails").toString()).get(0).toString()).getString("platformId");
//            quote.setPartyRoleId(partyRoleId);
//        }
        quoteRepository.saveAndFlush(quote);

        //询价成功更新要货跟踪信息
        invoke("stock.requireLogistics.sourceRequire.save",
                MapUtil.mapper("source",batuluInquireId,"origin",baturuPriceData.get("origin").toString(),
                        "message","向巴图鲁询价成功,询价单号【"+batuluInquireId+"】"));
    }

    // 服务方案转巴图鲁询价 - 推送询价
    private String pushBaturuInquire(Map data) {
        // 需要增加 用户标识
        data.put("userKey", baturuAccountInfoService.queryUserKey(data.get("store").toString()));
        Map sendBaturuData = data;
        Map carInfo = (Map) ((List) data.get("carInfos")).get(0);
        sendBaturuData.put("vinCode", carInfo.get("vinCode"));
        sendBaturuData.put("carType", carInfo.get("carType"));
        sendBaturuData.put("carPicture", MapUtil.mapper("nameplatePicture", carInfo.get("nameplatePicture"), "headPicture", carInfo.get("headPicture"), "trailPicture", carInfo.get("trailPicture")));
        sendBaturuData.remove("carBrandName");
        sendBaturuData.remove("carSystemName");
        sendBaturuData.remove("carManuFacturer");
        sendBaturuData.remove("carInfos");


        ((List) sendBaturuData.get("inquiryDetails")).forEach(inquiryDetail -> {
            Map inquiryDetailM = (Map) inquiryDetail;
            if ("[]".equals(inquiryDetailM.get("pictures"))) {
                inquiryDetailM.remove("pictures");
            } else if (!StringUtils.isEmpty(inquiryDetailM.get("pictures"))) {
                inquiryDetailM.put("pictures", JSONObject.parseArray(String.valueOf(inquiryDetailM.get("pictures"))));
            }
        });

        JSONObject result = baturuApi.publishInquire(sendBaturuData);
        if (!result.getString("state").equals("0")) {
            //巴图鲁询价错误将信息报错到报价单
            BusinessParam supplierNumber = businessParamRepository.findAllByQueryKey("baturuSupplierNumber").get(0);
            String[] split = supplierNumber.getValue().replace("[", "").replace("]", "").split(",");
            //根据供应商id和询价单号获取报价单
            Quote quote = quoteRepository.findOneByEnquiryAndSupplier(data.get("origin").toString(), split[0]);
            quote.setErrorMessage(result.getString("msg"));
            quoteRepository.saveAndFlush(quote);
            throw new RuntimeException(result.getString("msg"));
        }

        // 回写巴图鲁询价单号
        this.writeRequireMongoLog(MapUtil.mapper("data", sendBaturuData, "baturuId", result.getString("model")));
        return result.getString("model");
    }

    // 根据配件去重
    private <T> Predicate<T> distinctPartName(Function<? super T, T> currentData) {
        Map<Object, Boolean> existsKey = new ConcurrentHashMap<>();
        return t -> existsKey.putIfAbsent(currentData.apply(t), Boolean.TRUE) == null;
    }

    private List distinctPartName(List inquiryDetails) {
        List distinctBaturuItems = new ArrayList();
        List<String> disPartsNames = new ArrayList<>();
        inquiryDetails.stream().forEach(inquireDetail -> {
            JSONObject inquireDetailM = new JSONObject(((Map) inquireDetail));
            String partsCode = inquireDetailM.getString("partsCode");
            String partsName = inquireDetailM.getString("partsName");

            String disPartsName = "";
            if (StringUtils.isEmpty(partsCode)) {
                disPartsName = partsName;
            } else {
                disPartsName = partsName + partsCode;
            }

            if (!disPartsNames.contains(disPartsName)) {
                distinctBaturuItems.add(inquireDetail);
            }
            disPartsNames.add(disPartsName);
        });
        return distinctBaturuItems;
    }




    /**
     * 查询报价
     * 1. 多次调用存在修改已有数据的情况
     * */
    public void queryInquireResult(SimpleRequest request) {
        JSONObject jo = request.getJO();
        String userKey = baturuAccountInfoService.queryUserKey(jo.getString("storeId"));
        if (StringUtils.isEmpty(userKey)) return;
        List<BaturuInquire> baturuInquires = baturuInquireRepository.accordOriginFind(jo.getString("servicePlanId"));
        baturuInquires.forEach(bInquire -> {
            this.noticeOldSystemUpdateInquiry(userKey, bInquire);
            this.innerSave(bInquire);
        });
    }


    // 查询承运商
    public JSONArray queryCarrier(SimpleRequest request) {
        JSONObject jo = request.getJO();
        Set<Long> supplierIds = new HashSet<Long>();
        supplierIds.add(jo.getLongValue("EXTERNAL_GYSID"));

        JSONObject condi = new JSONObject();
        condi.put("userKey", baturuAccountInfoService.queryUserKey(jo.getString("MDID")));
        condi.put("supplierIds", supplierIds);
        JSONObject result = baturuApi.queryCarrier(condi);
        JSONArray model = result.getJSONArray("model");
        return model;
    }

    // 加入购物车
    public void addCart(SimpleRequest request) {
        JSONObject getJO = request.getJO();
        JSONArray servicePlanDatas = getJO.getJSONArray("item");
        String userKey = baturuAccountInfoService.queryUserKey(getJO.getString("MDID"));
        JSONArray baturuInquireDatas = servicePlanDatas.stream().filter(servicePlanData -> {
            JSONObject servicePlanItem = (JSONObject) servicePlanData;
            String oldInquiryNumber = servicePlanItem.getString("oldInquiryNumber");
            return StringUtils.hasText(oldInquiryNumber) && oldInquiryNumber.startsWith("BI");
        }).collect(Collectors.toCollection(JSONArray::new));
        if (baturuInquireDatas.isEmpty() || StringUtils.isEmpty(userKey)) return;

        // 根据询价单单号分组
        Map groupInquireBillM = baturuInquireDatas.stream().collect(Collectors.groupingBy(baturuInquireData -> {
            return ((JSONObject) baturuInquireData).getString("oldInquiryNumber");
        }));
        groupInquireBillM.forEach((k, v) -> {
            JSONObject sendBaturuCart = new JSONObject();
            Set priceNos = new HashSet();
            String baturuInquireId = baturuInquireRepository.findOne(k.toString()).getBaturuInquire();
            sendBaturuCart.put("userKey", userKey);
            sendBaturuCart.put("inquiryNo", baturuInquireId);
            sendBaturuCart.put("invoiceType", -1);
            servicePlanDatas.forEach(servicePlanData -> {
                priceNos.add(((JSONObject) servicePlanData).getString("uniqueValue"));
            });
            sendBaturuCart.put("priceNos", priceNos);
            baturuApi.addCart(sendBaturuCart);
        });
    }

    // 创建订单
    public JSONObject createOrder(SimpleRequest request) {
        JSONObject condi = request.getJO();
        condi.put("userKey", baturuAccountInfoService.queryUserKey(condi.getString("storeId")));
        JSONObject result = baturuApi.createOrder(condi);
        return result;
    }

    public void confirmReceipt(SimpleRequest request) {
        JSONObject condi = request.getJO();
        condi.put("userKey", baturuAccountInfoService.queryUserKey(condi.getString("storeId")));
        JSONObject result = baturuApi.confirmReceipt(condi);
    }


    // 查询报价 - 更新报价
    private void baturuUpdateInquire(BaturuInquire baturuInquire, JSONObject model) {
        baturuInquire.setExpiredTime(DateUtil.parse(DateUtil.timeStampToStr(model.getLong("expiredTime"))));
        baturuInquire.setQuoteStatus(model.getInteger("quoteStatus"));
        baturuInquire.setBeatBackReason(model.getString("beatBackReason"));
        baturuInquire.setRemark(model.getString("remark"));
    }

    // 查询报价 - 数据格式化【巴图鲁 --> 集群】
    private JSONArray baturuInquireResultFormat(BaturuInquire baturuInquire, JSONObject model) {
        JSONArray GYSXJDArray = new JSONArray();
        Set carInfos = baturuInquire.getCarInfos();
        BaturuInquireCarInfo carInfo = (BaturuInquireCarInfo) carInfos.iterator().next();

        model.getJSONArray("parts").forEach(part -> {
            JSONObject partObj = (JSONObject) part;

            // 返回的是一条明细？
            BaturuInquireItem inquireItem = baturuInquire.getInquiryDetails().stream().filter(singleInquireItem -> singleInquireItem.getThreePartyDetailCode().equals(partObj.getString("partsId"))).findFirst().orElse(null);
            if (ObjectUtils.isEmpty(inquireItem)) return;

            // 拼接报价数据
//            Set<BaturuInquireResult> inquireReqults = new HashSet<>();
//            BaturuInquireResult inquireReqult = this.appendBaturuInquireResult(partObj);
//            inquireReqult.setBaturuInquireItem(inquireItem);


            // 拼接老系统供应商询价单额外参数
            JSONObject generateGYSXJDData = new JSONObject();
            generateGYSXJDData.putAll(MapUtil.mapper("platformId", carInfo.getJekunModelCode(), "platformId", inquireItem.getPlatformId(), "productRule", inquireItem.isProductRule(), "storeId", baturuInquire.getStore(),
                    "carModelLabel", carInfo.getCarModelLabel(), "partsCode", inquireItem.getPartsCode(), "carLicense", carInfo.getCarLicense(), "expiredTime", DateUtil.format(new Date(model.getLong("expiredTime")), DateUtil.SHOW_DATETIME_FORMAT),
                    "originProduct", partObj.getString("partsId"), "origin", baturuInquire.getOrigin(), "originBusinessType", baturuInquire.getOriginBusinessType(), "vinCode", carInfo.getVinCode(), "baturuInquireId", baturuInquire.getId(), "jekunModelCode", carInfo.getJekunModelCode()));

            Set<BaturuInquireSupplier> inquireResultSuppliers = new HashSet<>();
            partObj.getJSONArray("prices").forEach(price -> {
                JSONObject priceObj = (JSONObject) price;
//                BaturuInquireSupplier inuqireSupplier = this.appendBaturuInquireSupplier(priceObj);
//                inuqireSupplier.setBaturuInquireResult(inquireReqult);
//                inquireResultSuppliers.add(inuqireSupplier);

                // 拼接老系统数据
                generateGYSXJDData.put("deliveryPlace", priceObj.getString("deliveryPlace"));
                GYSXJDArray.add(this.publishGYSJ(partObj, priceObj, generateGYSXJDData));
            });
          /*  if (!ObjectUtils.isEmpty(inquireResultSuppliers)) {
                inquireReqult.getBaturuInquireSuppliers().addAll(inquireResultSuppliers);
                inquireReqults.add(inquireReqult);
                inquireItem.getBaturuInquireResults().addAll(inquireReqults);
            }*/
        });

        this.baturuUpdateInquire(baturuInquire, model);
        return GYSXJDArray;
    }

    // 查询报价 - 拼接巴巴图鲁询价结果
    private BaturuInquireResult appendBaturuInquireResult(JSONObject partObj) {
        if (partObj.getJSONArray("prices").isEmpty() || partObj.getIntValue("beatBackReason") == 1) return new BaturuInquireResult();
        BaturuInquireResult inquireReqult = new BaturuInquireResult();
        inquireReqult.setModifiedPartsName(partObj.getString("modifiedPartsName"));
        inquireReqult.setQuotedPartsCode(partObj.getString("quotedPartsCode"));
        inquireReqult.setQuoteStatus(partObj.getInteger("quoteStatus"));
        inquireReqult.setBeatBackReason(partObj.getString("beatBackReason"));
        inquireReqult.setRemark(partObj.getString("remark"));
        return inquireReqult;
    }

    // 查询报价 - 拼接巴图鲁供应商报价的信息
    private BaturuInquireSupplier appendBaturuInquireSupplier(JSONObject priceObj) {
        BaturuInquireSupplier inquireResultSupplier = new BaturuInquireSupplier();
        inquireResultSupplier.setPriceNo(priceObj.getString("priceNo"));
        inquireResultSupplier.setSupplierId(priceObj.getLong("supplierId"));
        inquireResultSupplier.setQuotePrice(priceObj.getBigDecimal("quotePriceWithDiscount"));
        inquireResultSupplier.setFactoryType(priceObj.getInteger("factoryType"));
        inquireResultSupplier.setBrandName(priceObj.getString("brandName"));
        inquireResultSupplier.setOriginPlace(priceObj.getString("originPlace"));
        inquireResultSupplier.setGuaranteePeriod(priceObj.getFloat("guaranteePeriod"));
        inquireResultSupplier.setRemark(priceObj.getString("remark"));

        JSONObject deliveryInfo = priceObj.getJSONObject("deliveryInfo");
        if (!ObjectUtils.isEmpty(deliveryInfo) && !StringUtils.isEmpty(deliveryInfo)) {
            inquireResultSupplier.setDeliveryPlace(deliveryInfo.getString("deliveryPlace"));
            inquireResultSupplier.setArriveTime(deliveryInfo.getString("arriveTime"));
            inquireResultSupplier.setSupplierShippedPlan(deliveryInfo.getString("supplierShippedPlan"));
        }

        JSONObject bookGoodsInfo = priceObj.getJSONObject("bookGoodsInfo");
        if (!ObjectUtils.isEmpty(bookGoodsInfo) && !StringUtils.isEmpty(bookGoodsInfo)) {
            inquireResultSupplier.setBookGoods(priceObj.getInteger("isBookGoods") == 1?true:false);
            inquireResultSupplier.setBookGoodsDays(bookGoodsInfo.getInteger("bookGoodsDays"));
            inquireResultSupplier.setReturnable(bookGoodsInfo.getInteger("returnable") == 1?true:false);
        }
        return inquireResultSupplier;
    }

    private JSONObject publishGYSJ(JSONObject partObj, JSONObject priceObj, JSONObject otherInfo) {
        String partsName = partObj.getString("partsName");
        String quotedPartsCode = partObj.getString("quotedPartsCode");
        JSONObject data = new JSONObject();
        data.put("CJHM", otherInfo.getString("vinCode"));
        data.put("PART_NAME", StringUtils.hasText(quotedPartsCode)?partsName:quotedPartsCode);
        data.put("XJDH", otherInfo.getString("baturuInquireId"));
        data.put("JGYXQ", 3);
        data.put("YXQZ", otherInfo.get("expiredTime")); 
        data.put("HYZT", priceObj.getIntValue("isBookGoods") == 1?2:1);
        data.put("YXSDJ2", 0);
        data.put("XSSL", 0);
        data.put("XSJS", 0);
        data.put("XSXJ", 0);
        data.put("SB", 0);
        data.put("QRXZBJ", 1);
        data.put("SLDS", 0);
        data.put("LRL", 0);
        data.put("XSXJ2", 0);
        data.put("CBCYL", 0);
        data.put("FXTTJBJ", 0);
        data.put("WCBJ", 1);
        data.put("BXDSDJ", 0);
        data.put("XJLX", 1);
        data.put("RKDJ", priceObj.getDoubleValue("quotePriceWithDiscount"));
        data.put("WSCGCKJ", priceObj.getDoubleValue("quotePriceWithDiscount"));
        data.put("XSDJ", 0);
        data.put("XS4S", 0);
        data.put("LRL2", 0);
        data.put("XSDJ2", 0);
        data.put("KJHJS", 0);
        data.put("XCD", priceObj.get("originPlace"));
        data.put("XPPMC", priceObj.get("brandName"));
        String supplierShippedPlan = StringUtils.isEmpty(priceObj.getString("supplierShippedPlan"))?"":priceObj.getString("supplierShippedPlan");
        String remark = StringUtils.isEmpty(priceObj.getString("remark"))?"":priceObj.getString("remark");
        data.put("GYSBZ", remark + supplierShippedPlan);
        if (priceObj.getJSONObject("bookGoodsInfo") != null) {
            data.put("YJDHTS", priceObj.getJSONObject("bookGoodsInfo").getIntValue("bookGoodsDays") * 24);
        }

        data.put("EXTERNAL_GYSID", priceObj.getLongValue("supplierId"));

        data.put("WYZ", priceObj.get("priceNo"));
        data.put("UNIQUE_ID", priceObj.get("priceNo"));
        data.put("DELIVERY_PLACE", priceObj.get("deliveryPlace"));
        data.put("MDID", otherInfo.get("storeId"));
        data.put("FWMDID", otherInfo.get("storeId"));
        data.put("PTID", otherInfo.get("platformId"));
        data.put("DABJ", otherInfo.getBoolean("productRule")?1:0);
        data.put("QUERY_PZCXID", otherInfo.get("jekunModelCode"));
        data.put("QUERY_PZCXMC", otherInfo.get("carModelLabel"));
        data.put("QUERY_CPHM", otherInfo.get("carLicense"));
        data.put("QUERY_CJHM", otherInfo.get("vinCode"));
        data.put("YSPID", otherInfo.get("originProduct"));
        data.put("FWFAH", otherInfo.get("origin"));
        data.put("FWFALX", otherInfo.get("originBusinessType"));
        data.put("PART_CODE", quotedPartsCode);
        data.put("LJID", priceObj.get("quotedPartsCode"));
        data.put("ZBQ", priceObj.get("guaranteePeriod"));
        data.put("BATURU_BJSJ", DateUtil.format(priceObj.getDate("quoteTime"), DateUtil.SHOW_DATETIME_FORMAT) );
        data.put("BATURU_SCHQ_SJ", DateUtil.format(new Date(), DateUtil.SHOW_DATETIME_FORMAT));
        data.put("BATURU_ZHHQSJ", DateUtil.format(new Date(), DateUtil.SHOW_DATETIME_FORMAT));
        data.put("DSFPJMC", partObj.get("modifiedPartsName"));

        List systemEnvironments = baturuInquireRepository.findAll("SELECT VALUE FROM MAS_BUSINESS_PARAM WHERE ID = '20'");
        if ("pro".equals(systemEnvironments.get(0))) {
            data.put("GYSID", "00007011");
            data.put("GYSMC", "广州市巴图鲁信息科技有限公司(经销)");
        } else {
            data.put("GYSID", "00000286");
            data.put("GYSMC", "广州市巴图鲁信息科技有限公司");
        }

        JSONArray partsPictures = partObj.getJSONArray("pictures");
        partsPictures.addAll(priceObj.getJSONArray("supplierPictures"));
        String imgUrl = "[";
        for (int y = 0, yLen = partsPictures.size(); y < yLen; y++) {
            if (y != yLen - 1) {
                imgUrl += "{\"url\":\""+ partsPictures.get(y) +"\"},";
            } else {
                imgUrl += "{\"url\":\""+ partsPictures.get(y) +"\"}";
            }
        }
        imgUrl += "]";
        if (imgUrl.equals("[]")) imgUrl = "";
        data.put("THIRD_SUPPLIER_PICTURES", imgUrl);
        return data;


    }

    public void writeRequireMongoLog(Map param) {
//        Document column = new Document();
//        column.putAll(param);
//        column.put("currentDate", DateUtil.format(new Date(), DateUtil.SHOW_DATE_FORMAT));
//        SpringManager.getBean(MongoTemplate.class).getCollection("baturuPushInquire_temp").insertOne(column);
        String data = param.get("data").toString();
        String baturuId = param.get("baturuId").toString();
        try {
            BaturuPurshPriceLog log = new BaturuPurshPriceLog();
            log.setPayload(data);
            log.setAggregateId(baturuId);
            log.setId(SpringManager.getBean(SequenceService.class).getId("baturu_pursh_price_log"));
            SpringManager.getBean(BaturuPurshPriceLogRepository.class).save(log);
        } catch (Exception e) {

        }
    }

    // 巴图鲁通知需要获取报价
    public void baturuNoticeObtainInquiryData(SimpleRequest request) {
        this.inquiryNoticLogger(MapUtil.mapper("content", request.getJO()));
        SpringManager.getBean(OutboxSubscriberService.class).commonSendRequest("local:baturuInquireService.baturuNoticeObtainInquiryOutbox",  request.getJO().getString("data"), request.getJO());
    }

//    @OutboxSubscriber(id = "local:baturuInquireService.baturuNoticeObtainInquiryOutbox", name = "巴图鲁通知需要获取报价")
//    private void baturuNoticeObtainInquiryOutbox(OutboxPayloadWrapper outboxPayloadWrapper) {
//        JSONObject getJO = JSONObject.parseObject(outboxPayloadWrapper.getPayload());
//        BaturuInquire baturuInquire = baturuInquireRepository.accordBaturuInquiryIdFind(getJO.getString("data"));
//        String userKey = baturuAccountInfoService.queryUserKey(baturuInquire.getStore());
//        this.noticeOldSystemUpdateInquiry(userKey, baturuInquire);
//        this.innerSave(baturuInquire);
//    }

    // 写入 mongo 日志
    public void inquiryNoticLogger(Map param) {
        Document column = new Document();
        column.putAll(param);
        column.put("currentDate", DateUtil.format(new Date(), DateUtil.SHOW_DATETIME_FORMAT));
        mongoTemplate.getCollection("baturu_notice_inquiry").insertOne(column);
    }

    private void noticeOldSystemUpdateInquiry(String userKey, BaturuInquire baturuInquire) {
        JSONObject condi = new JSONObject(MapUtil.mapper("userKey", userKey, "inquiryNo", baturuInquire.getBaturuInquire(), "invoiceType", -1));
        JSONObject result = baturuApi.queryQuote(condi);
        JSONObject model = result.getJSONObject("model");
        if (ObjectUtils.isEmpty(model)) return;

        // 存在一个价格都没有返回的情况
        if (model.getJSONArray("parts").isEmpty()) {
            JSONObject deleteZXBCondi = new JSONObject();
            deleteZXBCondi.put("XJDH", baturuInquire.getId());
            piManager.synErp("scmGysxjdService.deleteAccordXJDHDeleteZXB", deleteZXBCondi);
            return;
        }

        JSONArray GYSXJDArray = this.baturuInquireResultFormat(baturuInquire, model);
        if (!GYSXJDArray.isEmpty()) {
            JSONObject gysxjd = new JSONObject(MapUtil.mapper("PUR_GYSXJDMX", GYSXJDArray));
            piManager.synErp("scmGysxjdService.updateBaturuInquire", gysxjd);
        }
    }

}













